<?php

namespace oa\services;

use Yii;
use oa\models\User;

class UserService extends BaseService
{

    public static function save($post, $id = 0)
    {
        if (empty($id)) {
            $model = new User();
            $model->scenario = User::SCENARIO_ADD;
        } else {
            $model = self::one($id);
            $model->scenario = User::SCENARIO_EDIT;
        }
        return $model->_save($post, 1);
    }

    public static function getList()
    {
        $req = Yii::$app->request;
        $query = User::find();
        $query->select('u.*,role.name role_name');
        $query->alias('u');
        $query->where('u.status<>-1 and u.role_id>0');
        $query->filterWhere(['u.status' => $req->get('status')]);
        $query->andFilterWhere(['u.mobile' => $req->get('mobile')]);
        $query->andFilterWhere(['like', 'u.realname', $req->get('realname')]);
        $query->andFilterWhere(['like', 'u.role_id', $req->get('role_id')]);
        $query->andFilterWhere(['>=', 'u.join_at', $req->get('join_at_min') ? strtotime($req->get('join_at_min')) : null]);
        $query->andFilterWhere(['<=', 'u.join_at', $req->get('join_at_max') ? strtotime($req->get('join_at_max')) : null]);
        $query->andFilterWhere(['>=', 'u.created_at', $req->get('created_at_min') ? strtotime($req->get('created_at_min')) : null]);
        $query->andFilterWhere(['<=', 'u.created_at', $req->get('created_at_max') ? strtotime($req->get('created_at_max')) : null]);
        $query->joinWith(['role role' => function($q) {
            $q->onCondition(['<>', 'role.status', -1]);
        }], false);
        $countQuery = clone $query;
        $query->orderBy(['u.created_at' => SORT_DESC]);
        $rows = $query->offset($req->get('offset'))->limit($req->get('limit'))->asArray()->all();
        foreach ($rows as $k => $v) {
            $rows[$k]['join_at'] = date('Y-m-d H:i', $v['join_at']);
            $rows[$k]['created_at'] = date('Y-m-d H:i', $v['created_at']);
        }
        return ['rows' => $rows, 'total' => $countQuery->count()];
    }

    public static function one($map, $toArray = 0)
    {
        $query = User::find()->where('status<>-1');
        if (is_numeric($map) && preg_match('/^[1-9]+[\d]*$/', $map)) {
            $query->andWhere('id=:id', [':id' => $map]);
        } elseif (is_array($map)) {
            $query->andWhere($map[0], $map[1]);
        } else {
            $query->andWhere($map);
        }
        if ($toArray == 1) {
            $query->asArray();
        }
        return $query->one();
    }

    public static function remove($id)
    {
        $model = self::one(['id=:id', [':id' => $id]]);
        $model->scenario = User::SCENARIO_REMOVE;
        return $model->_save();
    }

    public static function disable($id)
    {
        $model = self::one(['id=:id AND status=1', [':id' => $id]]);
        $model->scenario = User::SCENARIO_DISABLE;
        return $model->_save();
    }

    public static function enable($id)
    {
        $model = self::one(['id=:id AND status=2', [':id' => $id]]);
        $model->scenario = User::SCENARIO_ENABLE;
        return $model->_save();
    }

    public static function login()
    {
        $mobile = Yii::$app->request->post('mobile');
        $password = Yii::$app->request->post('password');
        $rememberMe = Yii::$app->request->post('rememberMe');

        $user = self::one(['mobile=:mobile', [':mobile' => $mobile]]);
        if($user && self::validatePasswd($password, $user->password)) {
            if (Yii::$app->user->login($user, isset($rememberMe) ? 3600 * 24 * 30 : 0)) {
                return true;
            }
            return '登录失败，请重试';
        }
        return '手机号或密码不正确';
    }

    public static function validatePasswd($password, $password_hash)
    {
        return Yii::$app->security->validatePassword($password, $password_hash);
    }

    public static function resetPassword($id)
    {
        $model = self::one($id);
        $model->scenario = User::SCENARIO_RESET_PASSWORD;
        if ($model->_save()) {
            return true;
        }
        return $model->errors();
    }

    public static function editPassword($id)
    {
        $new_password = Yii::$app->request->post('new_password');

        $model = self::one($id);
        $model->scenario = User::SCENARIO_EDIT_PASSWORD;
        $model->password = Yii::$app->security->generatePasswordHash($new_password);
        if ($model->_save()) {
            return true;
        }
        return $model->errors();
    }

    public static function changePassword()
    {
        $old_password = Yii::$app->request->post('old_password');
        $new_password = Yii::$app->request->post('new_password');

        if (self::validatePasswd($old_password, Yii::$app->user->identity->password)) {
            $adminUser = User::findOne(Yii::$app->user->id);
            $adminUser->scenario = 'changePasswd';
            $adminUser->password = Yii::$app->security->generatePasswordHash($new_password);
            if ($adminUser->save()) {
                return self::_success('修改成功');
            }
            return self::_success('修改失败');
        }
        return self::_success('原始密码不正确');
    }

    // 是否是超级管理员
    public static function isSuper()
    {
        return Yii::$app->user->identity->role_id == 0;
    }
}